MVC JsonResult with the [Authorize] attribute going to Logon but not displaying the view

Posted by likestoski on Stack Overflow See other posts from Stack Overflow or by likestoski
Published on 2012-03-22T17:10:20Z Indexed on 2012/03/22 17:29 UTC
Read the original article Hit count: 194

Filed under:
|
|

I am seeing odd behavior with MVC 3 methods that return a JsonResult when used with the Authorize attribute. What looks like happens is the Authorize is correctly evaluated when I am not logged in but instead of redirecting to the logon form the Json response is the logon form. Is there an addition attribute that directs the response to not return a value but instead redirect the user to the logon form, preferebly with the correct returnUrl value? What I did as a demo was to setup a new MVC3 site and added AspNetMembership to my DB using the aspnet_regsql.exe command. All that is setup and logging me in correctly. The behavior of the JsonResult doesn't seem right and I'm hoping I have just missed an attribute to make it work properly. Any help is greatly appreciated, thanks in advance.

Here is the Account Controller (leaving out the Post action which is not part of this question).

public class AccountController : Controller
{
    public ActionResult LogOn()
    {
        return View();
    }

    [Authorize]
    public JsonResult AuthorizedAction()
    {
        return Json("Only returns if I am authorized");
    }
}

Here is the Html markup:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnTest").click(function () {
            $.ajax({
                type: "POST",
                url: "Account/AuthorizedAction",
                data: {},
                success: function (result) {
                    $("#testMe").html(result);
                },
                error: function (result) {
                    $("#testMe").html('Something broke in the ajax request');
                }
            });             
        });
    });
</script>

<input type="button" id="btnTest" value="Test me" />
<div id="testMe">I have initial text</div>

The Result:

1) When logged in I get 'Only returns if I am authorized' in my test div 2) When not logged and I have a break point in my Logon() method I see this value Request["returnUrl"] "/Account/AuthorizedAction"

The test div I have displays the logon form :) this seems like I'm just not handling this properly.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JSON